package com.phoenix.jsef.framework;

import java.util.ArrayList;
import java.util.Map;

/**
 * 这个类作为AccessComponent的一个成员信息，帮助其维护关于查询中排序的信息
 * @author 李启联
 *
 */
public class AccessSorter {

	private final ArrayList sorters = new ArrayList();

	/**
	 * 清空排序列表
	 */
	public void clearSorter() {
		this.sorters.clear();
	}
	/**
	 * 增加一个排序字段
	 * @param sorterKey
	 * @param sorterDirection
	 * @return
	 */
	public boolean add(String sorterKey, String sorterDirection){
		return this.sorters.add( new AccessSorterItem(sorterKey, sorterDirection));
	}
	
	/**
	 * 增加一个排序字段，缺省为正序(ASC)
	 * @param sorterKey
	 * @return
	 */
	public boolean add(String sorterKey){
		return this.sorters.add(new AccessSorterItem(sorterKey, "ASC"));
	}

	public void add(Map<String, String> sortMap){
        sortMap.forEach((k,v)->{
            this.sorters.add(new AccessSorterItem(k, v));
        });
    }
	
	@Override
	public String toString(){
		StringBuilder orderbyClause = new StringBuilder();
		for(int i=0; i<sorters.size(); i++)
		{
			AccessSorterItem item = (AccessSorterItem)sorters.get(i);
			if(item != null)
			{
				orderbyClause.append(',');
				orderbyClause.append(item);
			}
		}
		if(orderbyClause.toString().startsWith(","))
			return orderbyClause.toString().substring(1).trim();
		
		return orderbyClause.toString().trim();
	}
	
	
}

class AccessSorterItem{
	
	String sorterKey;
	String sorterDirection;	
	AccessSorterItem(String sorterKey,String sorterDirection){
		this.sorterKey= sorterKey;
		this.sorterDirection =sorterDirection;
	}
	protected String getSorterKey() {
		return sorterKey;
	}
	protected String getSorterDirection() {
		return sorterDirection;
	}
	
	@Override
	public String toString(){
		return this.sorterKey +" " + this.sorterDirection;
	}
	
}
